import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Button,
  Paper,
  List,
  ListItem,
  ListItemText,
  ListItemAvatar,
  Avatar,
  Chip,
  alpha,
  useTheme,
  Divider,
  CircularProgress,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  IconButton,
  Badge,
} from '@mui/material';
import {
  Send as SendIcon,
  Description as DescriptionIcon,
  Work as WorkIcon,
  Person as PersonIcon,
  CheckCircle as CheckCircleIcon,
  Schedule as ScheduleIcon,
  Close as CloseIcon,
  Chat as ChatIcon,
} from '@mui/icons-material';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

interface InboxProps {
  inboxItems: any[];
  isLoading: boolean;
  error: string;
  isCompanyAdmin: boolean;
  onUpdate: () => void;
}

interface ChatItem {
  id: string;
  avatar?: string;
  name: string;
  lastMessage: string;
  timestamp: Date;
  unreadCount: number;
  isResume?: boolean;
  isJobPost?: boolean;
  userId?: number;
  companyId?: number;
  resumeStatus?: 'submitted' | 'read' | 'replied';
  jobPostId?: number;
}

interface Message {
  id: string;
  content: string;
  timestamp: Date;
  isFromMe: boolean;
  isSystemMessage?: boolean;
  resumeId?: number;
  jobPostId?: number;
  messageType?: 'text' | 'resume_submission' | 'status_update';
}

const Inbox: React.FC<InboxProps> = ({
  inboxItems,
  isLoading,
  error,
  isCompanyAdmin,
  onUpdate,
}) => {
  const theme = useTheme();
  const [chatList, setChatList] = useState<ChatItem[]>([]);
  const [selectedChat, setSelectedChat] = useState<ChatItem | null>(null);
  const [chatMessages, setChatMessages] = useState<Message[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [chatDialogOpen, setChatDialogOpen] = useState(false);
  const [loadingMessages, setLoadingMessages] = useState(false);

  useEffect(() => {
    // 处理聊天列表数据 - 按用户分组创建聊天会话
    if (inboxItems && inboxItems.length > 0) {
      const chatMap = new Map<string, ChatItem>();
      
      inboxItems.forEach(item => {
        let chatKey = '';
        let chatName = '';
        let chatAvatar = '';
        let otherUserId = 0;
        
        // 根据当前用户是否为企业负责人来确定聊天对象
        if (isCompanyAdmin) {
          // 企业负责人看到的是投递简历的用户
          if (item.applicant_id) {
            chatKey = `user_${item.applicant_id}`;
            chatName = item.applicant?.username || '求职者';
            chatAvatar = item.applicant?.avatar || '';
            otherUserId = item.applicant_id;
          }
        } else {
          // 普通用户看到的是企业负责人
          if (item.company_contact_id) {
            chatKey = `company_${item.company_contact_id}`;
            chatName = item.company?.name || '招聘企业';
            chatAvatar = item.company?.logo || '';
            otherUserId = item.company_contact_id;
          }
        }
        
        if (chatKey) {
          const existingChat = chatMap.get(chatKey);
          const itemTime = new Date(item.submitted_at || item.created_at || item.sent_at);
          
          if (!existingChat || itemTime > existingChat.timestamp) {
            // 确定最后一条消息内容
            let lastMessage = '';
            let resumeStatus: 'submitted' | 'read' | 'replied' = 'submitted';
            
            if (item.resume_id) {
              if (item.is_read) {
                resumeStatus = 'read';
                lastMessage = isCompanyAdmin ? '已查看简历' : '企业已查看您的简历';
              } else {
                lastMessage = isCompanyAdmin ? '收到新的简历投递' : '已投递简历';
              }
              
              if (item.feedback || item.reply_message) {
                resumeStatus = 'replied';
                lastMessage = item.feedback || item.reply_message || '收到回复';
              }
            } else {
              lastMessage = item.content || item.message || '消息';
            }
            
            chatMap.set(chatKey, {
              id: chatKey,
              avatar: chatAvatar,
              name: chatName,
              lastMessage,
              timestamp: itemTime,
              unreadCount: (!item.is_read && !isCompanyAdmin) ? 1 : 0,
              isResume: !!item.resume_id,
              isJobPost: !!item.job_post_id,
              userId: otherUserId,
              resumeStatus,
              jobPostId: item.job_post_id
            });
          }
        }
      });
      
      // 转换为数组并按时间排序
      const chats = Array.from(chatMap.values()).sort((a, b) => 
        b.timestamp.getTime() - a.timestamp.getTime()
      );
      
      setChatList(chats);
    } else {
      setChatList([]);
    }
  }, [inboxItems, isCompanyAdmin]);

  const handleChatClick = async (chat: ChatItem) => {
    setSelectedChat(chat);
    setChatDialogOpen(true);
    await loadChatMessages(chat);
  };

  const loadChatMessages = async (chat: ChatItem) => {
    setLoadingMessages(true);
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`/api/inbox/chat/${chat.userId}`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      if (response.ok) {
        const messages = await response.json();
        setChatMessages(messages);
      } else {
        // 如果API端点不存在，使用模拟数据
        const mockMessages: Message[] = [
          {
            id: '1',
            content: chat.isResume ? '您好，我对贵公司的职位很感兴趣，特此投递简历。' : '您好！',
            timestamp: new Date(Date.now() - 1000 * 60 * 30),
            isFromMe: !isCompanyAdmin,
            messageType: chat.isResume ? 'resume_submission' : 'text',
            resumeId: chat.isResume ? 1 : undefined
          }
        ];
        
        if (chat.resumeStatus === 'read') {
          mockMessages.push({
            id: '2',
            content: '我们已经收到并查看了您的简历，感谢您的投递。',
            timestamp: new Date(Date.now() - 1000 * 60 * 20),
            isFromMe: isCompanyAdmin,
            messageType: 'status_update'
          });
        }
        
        if (chat.resumeStatus === 'replied') {
          mockMessages.push({
            id: '3',
            content: '经过初步筛选，我们希望邀请您参加下周的面试，请确认您的时间安排。',
            timestamp: new Date(Date.now() - 1000 * 60 * 10),
            isFromMe: isCompanyAdmin,
            messageType: 'text'
          });
        }
        
        setChatMessages(mockMessages);
      }
    } catch (error) {
      console.error('加载聊天消息失败:', error);
      // 使用模拟数据作为后备
      const mockMessages: Message[] = [
        {
          id: '1',
          content: chat.isResume ? '您好，我对贵公司的职位很感兴趣，特此投递简历。' : '您好！',
          timestamp: new Date(Date.now() - 1000 * 60 * 30),
          isFromMe: !isCompanyAdmin,
          messageType: chat.isResume ? 'resume_submission' : 'text',
          resumeId: chat.isResume ? 1 : undefined
        }
      ];
      setChatMessages(mockMessages);
    } finally {
      setLoadingMessages(false);
    }
  };

  const handleSendMessage = async () => {
    if (!newMessage.trim() || !selectedChat) return;
    
    try {
      const token = localStorage.getItem('token');
      
      // 创建临时消息立即显示
      const tempMsg: Message = {
        id: `temp_${Date.now()}`,
        content: newMessage,
        timestamp: new Date(),
        isFromMe: true,
        messageType: 'text'
      };
      
      setChatMessages(prev => [...prev, tempMsg]);
      const messageToSend = newMessage;
      setNewMessage('');
      
      // 发送到API
      const response = await fetch('/api/inbox/message', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          recipientId: selectedChat.userId,
          content: messageToSend,
          messageType: selectedChat.isResume ? 'resume_feedback' : 'text',
          resumeSubmissionId: selectedChat.isResume ? selectedChat.id.split('_')[1] : undefined
        })
      });

      if (response.ok) {
        // 更新聊天列表中的最后一条消息
        setChatList(prev => prev.map(chat => 
          chat.id === selectedChat.id 
            ? { ...chat, lastMessage: messageToSend, timestamp: new Date() }
            : chat
        ));
        
        // 如果是简历反馈，更新简历状态
        if (selectedChat.isResume && isCompanyAdmin) {
          setSelectedChat(prev => prev ? { ...prev, resumeStatus: 'replied' } : null);
          setChatList(prev => prev.map(chat => 
            chat.id === selectedChat.id 
              ? { ...chat, resumeStatus: 'replied' as 'submitted' | 'read' | 'replied' }
              : chat
          ));
        }
      } else {
        console.error('发送消息失败');
        // 移除临时消息
        setChatMessages(prev => prev.filter(msg => msg.id !== tempMsg.id));
        setNewMessage(messageToSend); // 恢复消息内容
        alert('发送消息失败，请重试');
      }
      
    } catch (error) {
      console.error('发送消息失败:', error);
      alert('发送消息失败，请重试');
    }
  };

  const formatTime = (date: Date) => {
    const now = new Date();
    const diffInHours = (now.getTime() - date.getTime()) / (1000 * 60 * 60);
    
    if (diffInHours < 24) {
      return format(date, 'HH:mm', { locale: zhCN });
    } else if (diffInHours < 7 * 24) {
      return format(date, 'E', { locale: zhCN });
    } else {
      return format(date, 'MM/dd', { locale: zhCN });
    }
  };

  const getStatusIcon = (status?: string) => {
    switch (status) {
      case 'read':
        return <CheckCircleIcon fontSize="small" color="success" />;
      case 'replied':
        return <CheckCircleIcon fontSize="small" color="primary" />;
      default:
        return <ScheduleIcon fontSize="small" color="action" />;
    }
  };

  const renderChatItem = (chat: ChatItem) => {
    return (
      <ListItem
        key={chat.id}
        button
        onClick={() => handleChatClick(chat)}
        sx={{
          px: 2,
          py: 1.5,
          borderRadius: 2,
          mb: 0.5,
          transition: 'all 0.2s ease',
          '&:hover': {
            backgroundColor: alpha(theme.palette.primary.main, 0.08),
          },
        }}
      >
        <ListItemAvatar>
          <Badge
            badgeContent={chat.unreadCount > 0 ? chat.unreadCount : null}
            color="error"
            anchorOrigin={{
              vertical: 'top',
              horizontal: 'right',
            }}
          >
            <Avatar
              src={chat.avatar}
              sx={{
                width: 50,
                height: 50,
                bgcolor: chat.isResume ? theme.palette.info.main : 
                       chat.isJobPost ? theme.palette.success.main : 
                       theme.palette.primary.main
              }}
            >
              {chat.avatar ? undefined : 
               chat.isResume ? <DescriptionIcon /> :
               chat.isJobPost ? <WorkIcon /> :
               <PersonIcon />
              }
            </Avatar>
          </Badge>
        </ListItemAvatar>
        
        <ListItemText
          primary={
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography
                variant="subtitle1"
                sx={{
                  fontWeight: chat.unreadCount > 0 ? 600 : 400,
                  color: 'text.primary',
                }}
              >
                {chat.name}
              </Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Typography variant="caption" color="text.secondary">
                  {formatTime(chat.timestamp)}
                </Typography>
                {chat.isResume && getStatusIcon(chat.resumeStatus)}
              </Box>
            </Box>
          }
          secondary={
            <Box sx={{ display: 'flex', alignItems: 'center', mt: 0.5 }}>
              {chat.isResume && (
                <Chip
                  size="small"
                  icon={<DescriptionIcon fontSize="small" />}
                  label="简历投递"
                  color="info"
                  variant="outlined"
                  sx={{ mr: 1, height: 18, fontSize: '0.65rem' }}
                />
              )}
              {chat.isJobPost && (
                <Chip
                  size="small"
                  icon={<WorkIcon fontSize="small" />}
                  label="招聘"
                  color="success"
                  variant="outlined"
                  sx={{ mr: 1, height: 18, fontSize: '0.65rem' }}
                />
              )}
              <Typography
                variant="body2"
                color="text.secondary"
                sx={{
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  maxWidth: '200px'
                }}
              >
                {chat.lastMessage}
              </Typography>
            </Box>
          }
        />
      </ListItem>
    );
  };

  const renderMessage = (message: Message) => {
    const isFromMe = message.isFromMe;
    
    return (
      <Box
        key={message.id}
        sx={{
          display: 'flex',
          justifyContent: isFromMe ? 'flex-end' : 'flex-start',
          mb: 2,
        }}
      >
        <Paper
          elevation={1}
          sx={{
            p: 2,
            maxWidth: '70%',
            bgcolor: isFromMe ? theme.palette.primary.main : theme.palette.grey[100],
            color: isFromMe ? 'white' : 'text.primary',
            borderRadius: 2,
            ...(isFromMe ? {
              borderBottomRightRadius: 4,
            } : {
              borderBottomLeftRadius: 4,
            })
          }}
        >
          {message.messageType === 'resume_submission' && (
            <Box sx={{ mb: 1 }}>
              <Chip
                icon={<DescriptionIcon />}
                label="简历投递"
                size="small"
                color={isFromMe ? "secondary" : "primary"}
                variant="outlined"
              />
            </Box>
          )}
          
          <Typography variant="body1" sx={{ mb: 1 }}>
            {message.content}
          </Typography>
          
          <Typography
            variant="caption"
            sx={{
              opacity: 0.7,
              display: 'block',
              textAlign: 'right'
            }}
          >
            {format(message.timestamp, 'HH:mm')}
          </Typography>
        </Paper>
      </Box>
    );
  };

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h5" fontWeight={600}>
          我的消息
        </Typography>
        <Button 
          variant="contained" 
          color="primary" 
          startIcon={<ChatIcon />}
          onClick={() => {
            // 这里可以添加新建聊天的逻辑
            alert('新建聊天功能开发中...');
          }}
        >
          新建聊天
        </Button>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}

      <Paper
        elevation={0}
        sx={{
          borderRadius: 2,
          border: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
          overflow: 'hidden'
        }}
      >
        {isLoading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
            <CircularProgress />
          </Box>
        ) : chatList.length > 0 ? (
          <List sx={{ p: 1 }}>
            {chatList.map((chat, index) => (
              <React.Fragment key={chat.id}>
                {renderChatItem(chat)}
                {index < chatList.length - 1 && (
                  <Divider variant="inset" component="li" sx={{ ml: 8 }} />
                )}
              </React.Fragment>
            ))}
          </List>
        ) : (
          <Box sx={{ p: 4, textAlign: 'center' }}>
            <Typography color="text.secondary">
              暂无消息
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
              投递简历或收到消息后会显示在这里
            </Typography>
          </Box>
        )}
      </Paper>

      {/* 聊天对话框 */}
      <Dialog 
        open={chatDialogOpen} 
        onClose={() => setChatDialogOpen(false)}
        maxWidth="md"
        fullWidth
        PaperProps={{
          sx: { height: '70vh' }
        }}
      >
        <DialogTitle sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <Avatar src={selectedChat?.avatar} sx={{ width: 40, height: 40 }}>
              {selectedChat?.name?.charAt(0)}
            </Avatar>
            <Box>
              <Typography variant="h6">{selectedChat?.name}</Typography>
              {selectedChat?.isResume && (
                <Chip 
                  label={`简历状态: ${
                    selectedChat.resumeStatus === 'submitted' ? '已投递' :
                    selectedChat.resumeStatus === 'read' ? '已查看' : '已回复'
                  }`}
                  size="small"
                  color={
                    selectedChat.resumeStatus === 'submitted' ? 'default' :
                    selectedChat.resumeStatus === 'read' ? 'info' : 'success'
                  }
                />
              )}
            </Box>
          </Box>
          <IconButton onClick={() => setChatDialogOpen(false)}>
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        
        <DialogContent sx={{ display: 'flex', flexDirection: 'column', p: 0 }}>
          <Box sx={{ flex: 1, p: 2, overflowY: 'auto' }}>
            {loadingMessages ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
                <CircularProgress />
              </Box>
            ) : (
              chatMessages.map(renderMessage)
            )}
          </Box>
          
          <Divider />
          
          <Box sx={{ p: 2, display: 'flex', gap: 1 }}>
            <TextField
              fullWidth
              multiline
              maxRows={3}
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              placeholder="输入消息..."
              variant="outlined"
              size="small"
              onKeyPress={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault();
                  handleSendMessage();
                }
              }}
            />
            <Button
              variant="contained"
              onClick={handleSendMessage}
              disabled={!newMessage.trim()}
              sx={{ minWidth: 'auto', px: 2 }}
            >
              <SendIcon />
            </Button>
          </Box>
        </DialogContent>
      </Dialog>
    </Box>
  );
};

export default Inbox; 